package com.atguigu.flink.timer;

import com.atguigu.flink.pojo.WaterSensor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/11/25
 *
 * 计算每个传感器的平均水位
 */
public class Demo7_AggaregatingState
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
            .socketTextStream("hadoop103", 8888)
            .map(new MapFunction<String, WaterSensor>()
            {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(
                        data[0],
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2])
                    );
                }
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>()
            {

                private AggregatingState<WaterSensor, Double> state;

                @Override
                public void open(Configuration parameters) throws Exception {

                    state = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, MyAvg, Double>("avgVc", new AggregateFunction<WaterSensor, MyAvg, Double>()
                    {
                        @Override
                        public MyAvg createAccumulator() {
                            return new MyAvg();
                        }

                        @Override
                        public MyAvg add(WaterSensor value, MyAvg acc) {
                            acc.setCount(acc.getCount() + 1);
                            acc.setSumVc(acc.getSumVc() + value.getVc());
                            return acc;
                        }

                        @Override
                        public Double getResult(MyAvg acc) {
                            return acc.getSumVc() / acc.getCount();
                        }

                        @Override
                        public MyAvg merge(MyAvg a, MyAvg b) {
                            return null;
                        }
                    }, MyAvg.class));

                }

                @Override
                public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                    //来一条数据，放入状态
                    state.add(value);

                    //获取聚合后的结果
                    Double avgVC = state.get();

                    out.collect(ctx.getCurrentKey() + ":" + avgVC);

                }
            }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class MyAvg{

        private Integer count = 0;
        private Double sumVc = 0d;

    }
}
